<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="handleInput"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          :data="depts"
          :props="{ label: 'name'}"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          @current-change="handleCurrentChange"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <!-- <el-button v-if="$store.state.user.userInfo.roles.points.includes('add_employee')" size="mini" type="primary" @click="$router.push(`/employee/detail`)">添加员工</el-button> -->
          <el-button v-permission="'add_employee'" size="mini" type="primary" @click="$router.push(`/employee/detail`)">添加员工</el-button>

          <!-- <el-button v-if="$store.state.user.userInfo.roles.points.includes('excel_import')" size="mini" @click="showDialog=true">excel导入</el-button> -->
          <el-button v-permission="'excel_import'" size="mini" @click="showDialog=true">excel导入</el-button>

          <!-- <el-button v-if="$store.state.user.userInfo.roles.points.includes('excel_export')" size="mini" :loading="loading" @click="handleExport">excel导出</el-button> -->
          <el-button v-permission="'excel_export'" size="mini" :loading="loading" @click="handleExport">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <!-- 分页 -->
        <el-table :data="rows">
          <el-table-column align="center" label="头像">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <span v-else class="avatar"> {{ row.username.slice(2,3) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              <span>{{ row.formOfEmployment ===1? '正式' : '🐂🐎' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>

              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>

              <el-button size="mini" type="text">删除</el-button>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="page"
            @current-change="handlePageChange"
          />
        </el-row>

      </div>

      <ImportExcel v-model="showDialog" @refresh="getEmployeeList" />
      <el-dialog :visible.sync="showRoleDialog" title="分配角色">
        <!-- 弹层内容 -->
        <!-- checkbox -->
        <el-checkbox-group v-model="roleIds">
          <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
          <el-checkbox
            v-for="item in roleList"
            :key="item.id"
            :label="item.id"
          >{{ item.name }}</el-checkbox>
        </el-checkbox-group>

        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>

            <el-button size="mini" @click="showRoleDialog = false">取消</el-button>

          </el-col>

        </el-row>
      </el-dialog>

    </div>

  </div>

</template>

<script>
import { getdepartments } from '@/api/department'
import { transLate2TreeData } from '@/utils'
import { assignRole, getEmployeeDetail, getEmployeeList, getEnableRoleList, getFileData } from '@/api/employee'
import ImportExcel from './components/import-excel.vue'
import FileSaver from 'file-saver'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  /**
   * 组件的数据对象，包含了部门列表、选中的部门ID、总数、行数据、当前页码、搜索关键字和加载状态。
   * - `depts`: 存储部门信息的数组。
   * - `selectId`: 当前选中部门的ID。
   * - `total`: 数据的总数。
   * - `rows`: 当前页显示的数据行。
   * - `page`: 当前页码。
   * - `keyword`: 用户输入的搜索关键字。
   * - `loading`: 控制加载状态的布尔值。
   * 注：不需要在界面上显示或不需要响应式的数据，不需要在此声明以节省性能。
   */
  data() {
    return {
      depts: [],
      selectId: 0,
      total: 0,
      rows: [],
      page: 1,
      keyword: '',
      loading: false,
      showDialog: false,
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      currentUserId: null // 用来记录当前点击的用户id
      // timer: null   data中的数据不需要在界面中暂时或不需要响应式效果的时候  => 不需要在data中声明
      // 节省性能
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    async handleExport() {
      try {
        this.loading = true
        // 请求后端获取数据
        const res = await getFileData()
        // console.log(res)
        FileSaver.saveAs(res, '员工名单.xlsx')
      } catch {
        // 失败给提示
        this.$message.error('文件获取失败')
      } finally { // 无论成功失败 都要关闭loading
        this.loading = false
      }
    },
    handleInput() {
      // 利用防抖
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // 请求之前 重置页码
        this.page = 1
        this.getEmployeeList()
      }, 500)
    },
    handlePageChange(val) {
      // val是当前页码
      this.page = val
      // 重新获取选中部门下的员工数据
      this.getEmployeeList()
    },
    async getDepts() {
      const res = await getdepartments()
      // console.log(res)
      this.depts = transLate2TreeData(res, 0) // 转换为树形结构
      this.selectId = this.depts[0].id // 默认选中第一个部门
      // 用$nextTIck来保证树形组件渲染完成
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.selectId)
      })
      this.getEmployeeList()
    },
    handleCurrentChange(obj) {
      // console.log(obj)
      this.selectId = obj.id
      // 重置页码
      this.page = 1
      this.getEmployeeList() // 获取选中部门下的员工数据
    },
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList({
        departmentId: this.selectId,
        page: this.page,
        pagesize: 10, // 每页显示10条数据
        keyword: this.keyword
      })
      this.total = total
      this.rows = rows
    },
    // 点击角色按钮弹出层
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      // 记录当前点击的id 因为后边 确定取消要存取给对应的用户
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true // 调整顺序
    },
    // 点击角色按钮弹出层
    // async btnRole() {
    //   this.showRoleDialog = true
    //   this.roleList = await getEnableRoleList()
    // },
    // 点击角色的确定
    async  btnRoleOK() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}
.avatar {
  display: inline-block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #8df;

  text-align: center;
  line-height: 40px;
  color: #fff;
  font-size: 20px;
}
</style>
